package online.hxstart.code.concurrent.chapter01;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author huxing
 * @date 19-4-22 星期一 下午4:15
 * @describe
 */
public class RecordQuery {

  private final Connection connection;

  public RecordQuery(Connection connection) {
    this.connection = connection;
  }

  public <T> T query(RowHandler<T> handler, String sql, Object... params) throws SQLException {
    try (PreparedStatement statement = connection.prepareStatement(sql)) {
      int index = 1;
      for (Object param : params) {
        statement.setObject(index++, param);
      }
      ResultSet resultSet = statement.executeQuery();
      return handler.handle(resultSet);
    }
  }
}
